package com.yyg.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yyg.entity.EasyUser;
import com.yyg.entity.QueryInfo;
import com.yyg.mapper.UserMapper;
import com.yyg.service.EasyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private EasyUserService easyUserService;
    @Autowired
    private UserMapper udao;
    @RequestMapping("/alluser")
    public String getUserList(QueryInfo QueryInfo){
//        QueryWrapper qw=new QueryWrapper();
//        qw.like(QueryInfo.getQuery()!=null,"username",QueryInfo.getQuery());
//        IPage<EasyUser> iPage=easyUserService.page(new Page<>(QueryInfo.getPageNum(),QueryInfo.getPageSize()),qw);
//        System.out.println(iPage.getRecords());

        int numbers=udao.getUserCounts("%"+QueryInfo.getQuery()+"%");
        int pageStart=(QueryInfo.getPageNum()-1)*QueryInfo.getPageSize();

        List<EasyUser> users=udao.getAllUser("%"+QueryInfo.getQuery()+"%",pageStart,QueryInfo.getPageSize());
        HashMap<String,Object> res=new HashMap<>();
        res.put("number",numbers);
        res.put("data",users);
        String res_string = JSON.toJSONString(res);
        System.out.println("res>>>>>>>>>"+res_string);
        return res_string;
    }

    @RequestMapping("/state")
    public String updateUserState(@RequestParam("id")Integer id, @RequestParam("state") Boolean state){
        int i=udao.updateState(id,state);
        System.out.println("i?????????????????"+i);
        return i>0 ? "success":"error";
    }

    @RequestMapping("/addUser")
    public String addUser(@RequestBody EasyUser easyUser){
        easyUser.setRole("普通用户");
        easyUser.setState(false);
        int i = udao.addUser(easyUser);
        return i>0?"success":"error";
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(int id){
        int i=udao.deleteUser(id);
        return i>0 ?"success":"error";
    }

    @RequestMapping("/getupdate")
    public String getUpdateUser(int id){
        EasyUser user = udao.getUpdateUser(id);
        String string = JSON.toJSONString(user);
        return string;
    }

    @RequestMapping("/edituser")
    public String editUser(@RequestBody EasyUser user){
        int i = udao.editUser(user);
        return i>0 ?"success":"error";
    }
}
